﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using SiteManager;
using System.Data.SqlClient;
using Subgurim.Controles;

public partial class Doctor_NewDoctorAppointment : System.Web.UI.Page
{  // creating an instance of manager class
    Manager mgr = new Manager(true, "ConnectionString");
    Manager objManager = new Manager(true, "ConnectionString");
    Doctor objDoctor = new Doctor();
    int DoctorId = 0;
    int PatientId = 0;
    //string Title, Keywords, Description,desc;
    string desc;
    localFunction lfunction = new localFunction();
    public string GoolgeMapPath = "http://maps.google.com/maps?q=112+Vaughan+St%2c+%2c+Portland%2c+ME%2c+04102-3508&num=1&start=0"; //= "http://maps.google.com/maps?q=" + Server.UrlEncode(ds_drdet.Tables[0].Rows[0]["Address1"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["Address2"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["city"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["state"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["zipcode"].ToString()) + "&num=1&start=0";



    protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
           // int doctorId = Convert.ToInt32(Session["eventId"]);

            int eventID = 0;
            if (!string.IsNullOrEmpty(Request.QueryString["Id"]))
            {
                eventID = Convert.ToInt32(Request.QueryString["Id"]);
            }
            else
            {
                eventID = Convert.ToInt32(Session["eventId"]);
            }
            if (eventID != null)
            {
                GetDoctorsApointmentDetialsResult doc = CalenderRepository.GetDoctorsApointmentDetials(eventID);
               //IncreaseViewCounter();
                int docId = Convert.ToInt32(doc.doctorID);
                Session["dcotorId"] = docId.ToString();
                BindBoxes(docId);

            }
           
        }
        //linkViewPostMessage.Text = "Dr. " + lblName.Text + " Message Boards";
        //LinkButton2.Text = "Dr. " + lblName.Text + " Message Boards";

       
       

    }
    
    #region BindBoxes
    /// <summary>
    /// to get all the details of the specified doctor and fill the controls
    /// </summary>
    /// <param name="id"></param>
    private void BindBoxes(int id)
    {
        //to get all the details of the specified doctor
        double overallRate = 0;
        //   try
        {
           // int doctorId = Convert.ToInt32(Session["eventId"]);
            int eventID = 0;
            if (!string.IsNullOrEmpty(Request.QueryString["Id"]))
            {
                eventID = Convert.ToInt32(Request.QueryString["Id"]);
            }
            else
            {
                eventID = Convert.ToInt32(Session["eventId"]);
            }

            GetDoctorsApointmentDetialsResult doc = CalenderRepository.GetDoctorsApointmentDetials(eventID);
            var timeStart = doc.eventstart.Value.TimeOfDay;
            var timeEnd = doc.eventend.Value.TimeOfDay;
            var date = doc.eventstart.Value.Date;
            var dayofWeek = doc.eventstart.Value.DayOfWeek;
            var day = doc.eventstart.Value.Day;
            var month = doc.eventstart.Value.Month;
            var year = doc.eventstart.Value.Year;
            int did = Convert.ToInt32(doc.doctorID);
            int dr_id = did;
            lblDate.Text = ("" + month + "/" + day + "/" + year + "").ToString();
            //lblDate.Text = date.ToString();
            lblDay.Text = dayofWeek.ToString();
            lblStartTime.Text = timeStart.ToString();
            lblEndTime.Text = timeEnd.ToString();
            SqlParameter[] sqlParam = new SqlParameter[1];
            sqlParam[0] = new SqlParameter("@dr_id", SqlDbType.Int);
            sqlParam[0].Value = id;
            DataSet ds_drdet = CustomRepository.CustumDataSetFunction("get_doctordetails", sqlParam, "tbl_a");


            if (ds_drdet.Tables[0].Rows.Count > 0)
            {
                // NEW CODE ADDED TO SET VISIBILITY OF 'SEND MAIL' LINK ACCORDING TO DOCTOR'S SUBSCRIPTION TYPE\
                // ADDED ON 27TH DECEMBER 2007
                //if (ds_drdet.Tables[0].Rows[0]["featureType"].ToString() == "" || ds_drdet.Tables[0].Rows[0]["featureType"].ToString() == "0")
                //{
                //    lnkSendMail.Visible = false;
                //}
                // 

                lblName.Text = ds_drdet.Tables[0].Rows[0]["Name"].ToString();
                lblTitle.Text = ds_drdet.Tables[0].Rows[0]["Title"].ToString();
                litReviews.Text = ds_drdet.Tables[0].Rows[0]["patientreview"].ToString();
                //mod by s
                //lblmgrActivity.Text = "Not Available";
                if (ds_drdet.Tables[0].Rows[0]["MajorActivityID"].ToString() != "0")
                    //lblmgrActivity.Text = ds_drdet.Tables[0].Rows[0]["MajorActivityID"].ToString();
                //lblgroupprac.Text = ds_drdet.Tables[0].Rows[0]["GroupPractice"].ToString().Length > 0 ? ds_drdet.Tables[0].Rows[0]["GroupPractice"].ToString() : "Not Available";
                //lbllanguage.Text = ds_drdet.Tables[0].Rows[0]["languages"].ToString().Length > 0 ? ds_drdet.Tables[0].Rows[0]["languages"].ToString() : "Not Available";
                //end
                // Response.Write(ds_drdet.Tables[0].Rows[0]["Address1"].ToString());
                lblAddress.Text += ds_drdet.Tables[0].Rows[0]["Address1"].ToString();
                if (ds_drdet.Tables[0].Rows[0]["Address2"].ToString().Trim().Length > 0)
                    lblAddress.Text += "<br>" + ds_drdet.Tables[0].Rows[0]["Address2"].ToString();

                if (ds_drdet.Tables[0].Rows[0]["City"].ToString().Trim().Length > 0)
                    lblAddress.Text += "<br>" + ds_drdet.Tables[0].Rows[0]["City"].ToString();
                if (ds_drdet.Tables[0].Rows[0]["State"].ToString().Trim().Length > 0)
                    lblAddress.Text += ", " + ds_drdet.Tables[0].Rows[0]["State"].ToString();
                if (ds_drdet.Tables[0].Rows[0]["ZipCode"].ToString().Trim().Length > 0)
                    lblAddress.Text += " " + ds_drdet.Tables[0].Rows[0]["ZipCode"].ToString();
                if (ds_drdet.Tables[0].Rows[0]["Phone"].ToString().Trim().Length > 0)
                    lblAddress.Text += "<br>Phone :" + ds_drdet.Tables[0].Rows[0]["Phone"].ToString();
                if (ds_drdet.Tables[0].Rows[0]["Fax"].ToString().Trim().Length > 0)
                    lblAddress.Text += "<br>Fax :" + ds_drdet.Tables[0].Rows[0]["Fax"].ToString();
                try
                {

                   // string fulladdress = string.Format(ds_drdet.Tables[0].Rows[0]["Address1"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["Address2"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["city"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["state"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["zipcode"].ToString());
                   // string skey = ConfigurationManager.AppSettings["googlemaps.subgurim.net"];
                    //GeoCode geocode;
                   // geocode = GMap1.getGeoCodeRequest(fulladdress);
                   // var glatlng = new Subgurim.Controles.GLatLng(geocode.Placemark.coordinates.lat, geocode.Placemark.coordinates.lng);
                    //GMap1.setCenter(glatlng, 8, Subgurim.Controles.GMapType.GTypes.Normal);
                    //var oMarker = new Subgurim.Controles.GMarker(glatlng);
                   // GMap1.addGMarker(oMarker);    
                        




                    
                    //GoolgeMapPath = "http://maps.google.com/maps?q=" + Server.UrlEncode(ds_drdet.Tables[0].Rows[0]["Address1"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["Address2"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["city"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["state"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["zipcode"].ToString()) + "&num=1&start=0";
                   // googlMap.Attributes.Add("src", GoolgeMapPath);
                    // googlMap.src;
                    
                    //googlMap.
                    
                    // GetUrl(GoolgeMapPath);
                    lnkGoogle.NavigateUrl = "http://maps.google.com/maps?q=" + Server.UrlEncode(ds_drdet.Tables[0].Rows[0]["Address1"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["Address2"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["city"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["state"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["zipcode"].ToString()) + "&num=1&start=0";
                    lnkGoogle1.NavigateUrl = "http://maps.google.com/maps?q=" + Server.UrlEncode(ds_drdet.Tables[0].Rows[0]["Address1"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["Address2"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["city"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["state"].ToString() + ", " + ds_drdet.Tables[0].Rows[0]["zipcode"].ToString()) + "&t=h&num=1&start=0&hl=en";
                }
                catch { }
                Rating1.rating = Convert.ToDecimal(ds_drdet.Tables[0].Rows[0]["peerref"].ToString());
                Rating1.totalScore = 15;

                //lblMedicalSchool.Text = "Not Available";

                //if (ds_drdet.Tables[0].Rows[0]["MedicalSchool"].ToString().Trim().Length != 0)
                //    lblMedicalSchool.Text = ds_drdet.Tables[0].Rows[0]["MedicalSchool"].ToString();

              

                string[] strHosids = ds_drdet.Tables[0].Rows[0]["HospitalName"].ToString().Split(new char[] { ',' });
                if (ds_drdet.Tables[0].Rows[0]["HospitalName"].ToString() != "")
                {
                    //DataSet dshos = mgr.ExecuteQuery("select HName from tbl_hospitals where id=" + ds_drdet.Tables[0].Rows[0]["HospitalName"].ToString(), "tbl");
                    DataSet dshos = CustomRepository.CustumDataSetFunction("select HName from tbl_hospitals where id in (select hospital_id from tbl_doctor_hospital where dr_id="
                        + id.ToString() + ");", "Hospitals");
                    if (dshos.Tables[0].Rows.Count > 0)
                    {
                        //lblHospital.Text = dshos.Tables[0].Rows[0]["HName"].ToString();

                        //changed as per client's request : K
                        //December 2, 20006
                        //lblHospital.Text = "";
                        //for (int i = 0; i <= dshos.Tables[0].Rows.Count - 1; i++)
                        //{
                        //    lblHospital.Text += dshos.Tables[0].Rows[i]["HName"].ToString() + "<br>";
                        //}
                        //lblHospital.Text = lblHospital.Text.Substring(0, lblHospital.Text.Length - 4);
                    }
                    else
                    {
                        //lblHospital.Text = "None";
                    }

                }
                else
                {
                    //lblHospital.Text = "Not Available";
                }
                

                if (ds_drdet.Tables[0].Rows[0]["overallrate"].ToString() != null && ds_drdet.Tables[0].Rows[0]["overallrate"].ToString() != "")
                {
                    overallRate = Convert.ToDouble(ds_drdet.Tables[0].Rows[0]["overallrate"]);
                    if (overallRate > 100)
                        overallRate = 100;

                    float fRateLimit = Convert.ToSingle(ConfigurationManager.AppSettings["MinRatingLimit"].ToString());
                   
                }

                //if (Convert.ToInt32(ds_drdet.Tables[0].Rows[0]["featured"].ToString()) > 0)
                //{
                    string str_path = String.Empty;
                    if (System.IO.File.Exists(Request.PhysicalApplicationPath + "/images/Dr_images/" + ds_drdet.Tables[0].Rows[0]["photo"].ToString()))
                    {
                        if (ds_drdet.Tables[0].Rows[0]["photo"].ToString().Trim().Length > 0)
                        {
                            str_path = getThumbnaleImageWithURLFormat(ds_drdet.Tables[0].Rows[0]["photo"].ToString(), 250, 200, false, "", Session["strHTTP"].ToString());
                        }
                        else
                        {
                            str_path = getThumbnaleImageWithURLFormat("silhouette-male.gif", 80, 100, false, "", Session["strHTTP"].ToString());
                            //string str_path = mgr.getThumbnaleImage("../images/Dr_images/" + ds_drdet.Tables[0].Rows[0]["photo"].ToString(), 130, 100, false, "");                   
                        }
                    }
                    else
                    {
                        str_path = getThumbnaleImageWithURLFormat("silhouette-male.gif", 80, 100, false, "", Session["strHTTP"].ToString());
                        //string str_path = mgr.getThumbnaleImage("../images/Dr_images/" + ds_drdet.Tables[0].Rows[0]["photo"].ToString(), 130, 100, false, "");                   
                    }

                    gender.Text = ds_drdet.Tables[0].Rows[0]["gender"].ToString();
                    imgTag.Text = str_path;
                if (ds_drdet.Tables[0].Rows[0]["profile_desc"].ToString().Length > 0)
                    {
                        lbl_about.Text = "<b>About this Doctor</b>  : " + ds_drdet.Tables[0].Rows[0]["profile_desc"].ToString();
                    }
                    lbl_web.Text = "<a href='" + ds_drdet.Tables[0].Rows[0]["web"].ToString() + "' target='_blank'>" + ds_drdet.Tables[0].Rows[0]["web"].ToString() + "</a>";
                //}
                /*else
                {
                    img_dr.Visible = false;
                }*/


                //Doctor Endorsement
                lbl_endorse.Text = ds_drdet.Tables[0].Rows[0]["countpeerref"].ToString();




                //Overall Rating

                SqlParameter[] sqlParamRate = new SqlParameter[1];
                sqlParamRate[0] = new SqlParameter("@dr_id", SqlDbType.Int);
                sqlParamRate[0].Value = id;
                DataSet dsRating = CustomRepository.CustumDataSetFunction("get_ratingbydrid", sqlParamRate, "tbl");

                decimal strMedicalSchoolRate = 0.0M;
                decimal strResidencyRate = 0.0M;
                decimal fello = 0.0M;
                if (dsRating.Tables[0].Rows.Count > 0)
                {
                    if (dsRating.Tables[0].Rows[0]["fell"].ToString() != "")
                    {

                    }

                }


                //***************************************************************************************************
                //***************************************************************************************************
            }
            else
            {
                MultiView1.SetActiveView(View2);
                lblMsg.Text = "No Records found";
                lblMsg.ForeColor = System.Drawing.Color.Red;
                lblMsg.Font.Bold = true;
            }
        }
        // catch (Exception ex)
        {
            //   Response.Write(ex.Message);
        }
    }
    
    #endregion

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect(Session["strHttp"] + "patient/PatientCalendar.aspx?Id="+Session["dcotorId"], true);

    }
    protected void linkViewPostMessage_Click(object sender, EventArgs e)
    {
        //Redirect the page
        string Identity = "";
        Encryption objEncription = new Encryption();

        //Identity =Request.QueryString["Id"].ToString();   at 170908  

        //Added at 180908

        if (Request.QueryString["Id"] != null)
        {
            Identity = Request.QueryString["Id"].ToString();
        }
        else if (RewriteModule.RewriteContext.Current.Params["Id"] != null)
        {
            Identity = RewriteModule.RewriteContext.Current.Params["Id"].ToString();
        }


        //Ebd 180908

        Identity += ",2";
        Identity = objEncription.QueryStringEncode(Identity);
        if (Session["pageFromOrAction"] != null || Session["pageFromOrAction"].ToString() == "")
        {
            Response.Redirect(Session["strHttp"] + "MessageBoard/ViewMessage.aspx?id=" + Identity);
        }
    }


    protected void lnk_rate_Click(object sender, EventArgs e)
    {
       
        int dr_id = 0;
        if (Request.QueryString["Id"] != null)
        {
            dr_id = Convert.ToInt32(Request.QueryString["Id"].ToString());
        }
        else if (RewriteModule.RewriteContext.Current.Params["Id"] != null)
        {
            dr_id = Convert.ToInt32(RewriteModule.RewriteContext.Current.Params["Id"].ToString());
        }


       
        Response.Redirect(Session["strHttp"] + "Doctor/RateDoctors.aspx?id=" + dr_id);
        
    }
    protected void lnlAddtoMyDoctors_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["Id"] != null)
        {
            Response.Redirect(Session["strHttp"] + "User/MyDoctors.aspx?id=" + Request.QueryString["Id"]);
        }
        else if (RewriteModule.RewriteContext.Current.Params["Id"] != null)
        {
            Response.Redirect(Session["strHttp"] + "User/MyDoctors.aspx?id=" + RewriteModule.RewriteContext.Current.Params["Id"]);
        }

    }
    protected void linkLogin_Click(object sender, EventArgs e)
    {

    }
    public void IncreaseViewCounter()
    {
        //Manager objManager = new Manager(true, "ConnectionString");

        if (Session["userID"] != null && !Session["userID"].ToString().Length.Equals(0))
        {
            //if (Convert.ToInt32(Session["userID"]) == Convert.ToInt32(Request.QueryString["Id"]))at 170908

            if ((Convert.ToInt32(Session["userID"]) == Convert.ToInt32(Request.QueryString["Id"])) || (Convert.ToInt32(Session["userID"]) == Convert.ToInt32(RewriteModule.RewriteContext.Current.Params["Id"])))
            {
                return;
            }
        }
        else
        {
            SqlParameter[] objSqlParameter = new SqlParameter[2];
            objSqlParameter[0] = new SqlParameter("@DoctorID", SqlDbType.BigInt);
            if (Request.QueryString["Id"] != null && Request.QueryString["Id"].ToString() != "")
            {
                objSqlParameter[0].Value = Convert.ToInt32(Request.QueryString["Id"]);
            }
            else if (RewriteModule.RewriteContext.Current.Params["Id"] != null)
            {
                objSqlParameter[0].Value = Convert.ToInt32(RewriteModule.RewriteContext.Current.Params["Id"]);
            }

            objSqlParameter[1] = new SqlParameter("@DoctorType", SqlDbType.BigInt);
            objSqlParameter[1].Value = 2;
            //objManager.ExecuteQuery("AddAndUpdateProfileView", objSqlParameter);
            SqlDataReader dr = CustomRepository.CustumExecutQuery("AddAndUpdateProfileView", objSqlParameter);
            ////objManager = null;
        }

    }
    protected void lnkMyMessageBoard_Click(object sender, EventArgs e)
    {
        Response.Redirect(Session["strHttp"] + "DashBoard/MyMessageBoard.aspx");
    }
    protected void lnkMyMessageBoard_Click1(object sender, EventArgs e)
    {

    }
    /// <summary>
    /// Event handlar for Send mail to feature doctor
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lnkSendMail_Click(object sender, EventArgs e)
    {
        //Response.Redirect(Session["strHttp"]+"LeadGeneration/MailFeatureDoc.aspx?DoctorID="+Convert.ToInt32(Request.QueryString["id"])); at 170908
        if (Request.QueryString["Id"] != null)
        {
            Response.Redirect(Session["strHttp"] + "LeadGeneration/MailFeatureDoc.aspx?DoctorID=" + Convert.ToInt32(Request.QueryString["Id"]));
        }
        else if (RewriteModule.RewriteContext.Current.Params["Id"] != null)
        {
            Response.Redirect(Session["strHttp"] + "LeadGeneration/MailFeatureDoc.aspx?DoctorID=" + Convert.ToInt32(RewriteModule.RewriteContext.Current.Params["Id"]));
        }

    }

    public string getThumbnaleImageWithURLFormat(string imgName, int maxWidth, int maxHeight, bool saveImage, string savePath, string baseURL)
    {
        string s;
        double imgHeight, imgWidth;
        //Response.Write(imgName) ;
        s = Server.MapPath("~/images/dr_images/" + imgName);
        //Response.Write("</br>"+s);
        System.Drawing.Image currentImage = System.Drawing.Image.FromFile(s);
        imgHeight = currentImage.Height;
        imgWidth = currentImage.Width;
        if (imgWidth > maxWidth | imgHeight > maxHeight)
        {
            double deltaWidth = imgWidth - maxWidth;
            double deltaHeight = imgHeight - maxHeight;
            double scaleFactor;
            if (deltaHeight > deltaWidth)
                scaleFactor = maxHeight / imgHeight;
            else
                scaleFactor = maxWidth / imgWidth;
            imgWidth *= scaleFactor;
            imgHeight *= scaleFactor;
        }

        if (saveImage)
        {
            if (savePath == "")
                throw new Exception("must pass a file name");
            currentImage.GetThumbnailImage(Convert.ToInt32(imgWidth), Convert.ToInt32(imgHeight), null, IntPtr.Zero).Save(Server.MapPath(savePath));
            currentImage.Dispose();
        }
        //return currentImage.GetThumbnailImage(Convert.ToInt32(imgWidth), Convert.ToInt32(imgHeight), null, IntPtr.Zero);


        //return ("<img src=\"" + baseURL + "images/dr_images/" + imgName + "\"" + " height=\"" + imgHeight + "\" width=\"" + imgWidth + "\" border='0' alt=''/>");
        return ("<img src=\"" + baseURL + "images/dr_images/" + imgName + "\"" + " height=\"" + maxHeight + "\" width=\"" + maxWidth + "\" border='0' alt=''/>");
    }
}
